﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using NHTU;
using DevComponents.DotNetBar;

namespace NOMFinalSettlement.AppForm.App
{
    public partial class fUser : Office2007Form
    {
        private FinalSettlementModel.User UserDB = null;
        private FinalSettlementModel.Permissions UserPer = null;
        private int idSelected = -1;
        private int currentRowSelect = -1;
        private bool isMasterSelect = false;

        public fUser()
        {
            InitializeComponent();
            MainApp.Self.appProcess.clientPermission();
        }

        private void fUser_Load(object sender, EventArgs e)
        {
            //Khởi tạo lớp User mới từ formload
            UserDB = new FinalSettlementModel.User();
            UserPer = new FinalSettlementModel.Permissions();

            // Đăng ký sự kiện
            UserDB.EventLoadData += new FinalSettlementModel.User.LoadData(OnLoadUserData);

            //Load data
            DataUserToGrid();

        }

        void OnLoadUserData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.User.LoadData tmpDelegate = new FinalSettlementModel.User.LoadData(OnLoadUserData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            //Hàm xử lý
            DataUserToGrid();            
        }

        #region "Hàm xử lý dữ liệu"
        private void DataUserToGrid()
        {
            
            listUser.Rows.Clear();

            DataTable dt = UserDB.ListUserData();

            foreach (DataRow row in dt.Rows)
            {
                string master = ((bool)row["Master"] == true) ? "Quản trị hệ thống" : "Người dùng";

                var img = ((bool)row["Lock"] == false) ? Properties.Resources.iconUser16 : Properties.Resources.iconUserGray16;

                string statusText = ((bool)row["Lock"] == true) ? "Đang khóa" : "Đang sử dụng";
                if(listUser.ColumnCount>0)
                {
                    listUser.Rows.Add(row["ID"], img, row["Username"], row["Fullname"], statusText, master, row["Address"], row["Phone"], row["Email"]);
                }
            }
        }

        private void DataUserPermission()
        {
            if (idSelected > 0)
            {
                var userPermission = UserPer.permissionUser(idSelected);
                foreach (var per in userPermission)
                {
                    setCheckbox(per.TiepNhanHoSo,
                                per.GiaoHoSo,
                                per.DuLieuHeThong,
                                per.NguoiDung,
                                per.SaoLuu,
                                per.PhucHoi,
                                per.GiaoDien,
                                per.TrinhPheDuyet,
                                per.PheDuyetQT,
                                per.BCTongHop,
                                per.BCHoSoMoi,
                                per.BCTinhHinhQT,
                                per.BCTinhHinhHSChuaQT,
                                per.BCChiTietHSChuaQT,
                                per.BCChiTietHSDaQT);
                }
            }
        }

        private void doDelete()
        {
            if (true == isMasterSelect)
            {
                MsgBox.Show("Không thể xóa tài khoản này","Thông báo",MsgBoxButton.Ok,MsgBoxIcon.Warning);
                return;
            }
            if (MsgBox.Show("Bạn có chắc chắn muốn xoá dữ liệu này không ?", "Thông Báo",
                 MsgBoxButton.YesNo, MsgBoxIcon.Question) == MsgBoxResult.Yes)
            {
                UserPer.deletePermission(idSelected);
                UserDB.deleteUser(idSelected);                
            }
        }

        private void doSave()
        {
            if (! UserDB.checkUserExist(txtUserName.Text.Trim()))
            {
                UserDB.insertUser(txtFullName.Text,
                                    txtUserName.Text,
                                    Hash.Md5(txtPassWord.Text.Trim()),
                                    txtAddress.Text,
                                    txtPhone.Text,
                                    txtEmail.Text,
                                    false,
                                    chbActive.Checked);

                UserPer.addNewPermission(UserDB.userIdentity,
                                    chbTiepNhanHoSo.Checked,
                                    chbGiaoHoSo.Checked,
                                    chbDuLieuHeThong.Checked,
                                    chbNguoiDung.Checked,
                                    chbSaoLuu.Checked,
                                    chbPhucHoi.Checked,
                                    chbGiaoDien.Checked,
                                    chbTrinhPheDuyet.Checked,
                                    chbPheDuyetQT.Checked,
                                    chbBCTongHop.Checked,
                                    chbBCHoSoMoi.Checked,
                                    chbBCTinhHinhQT.Checked,
                                    chbBCTinhHinhHSChuaQT.Checked,
                                    chbBCChiTietHSChuaQT.Checked,
                                    chbBCChiTietHSDaQT.Checked);
                //DataUserToGrid(); bắt sự kiện rồi, không cần gọi lại nữa
                reloadControl();
            }
            else MsgBox.Show("Tên đăng nhập đã tồn tại. Vui lòng nhập dữ liệu khác!","Thông Báo",MsgBoxButton.Ok,MsgBoxIcon.Stop);
        }

        private void doUpdate()
        {
            if (UserDB.checkUserExist(txtUserName.Text.Trim()))
            {
                UserDB.updateUser(idSelected,
                                    txtFullName.Text,
                                    txtUserName.Text,
                                    txtPassWord.Text.Trim(),
                                    txtAddress.Text,
                                    txtPhone.Text,
                                    txtEmail.Text,
                                    isMasterSelect,
                                    !chbActive.Checked);

                UserPer.updatePermission(idSelected,
                                    chbTiepNhanHoSo.Checked,
                                    chbGiaoHoSo.Checked,
                                    chbDuLieuHeThong.Checked,
                                    chbNguoiDung.Checked,
                                    chbSaoLuu.Checked,
                                    chbPhucHoi.Checked,
                                    chbGiaoDien.Checked,
                                    chbTrinhPheDuyet.Checked,
                                    chbPheDuyetQT.Checked,
                                    chbBCTongHop.Checked,
                                    chbBCHoSoMoi.Checked,
                                    chbBCTinhHinhQT.Checked,
                                    chbBCTinhHinhHSChuaQT.Checked,
                                    chbBCChiTietHSChuaQT.Checked,
                                    chbBCChiTietHSDaQT.Checked);

                //DataUserToGrid(); bắt sự kiện rồi, không cần gọi lại nữa
                idSelected = -1;
                reloadControl();
            }
            else MsgBox.Show("Tên đăng nhập đã tồn tại. Vui lòng nhập dữ liệu khác!", "Thông Báo", MsgBoxButton.Ok, MsgBoxIcon.Stop);
        }

        #endregion


        private void listUser_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            idSelected = MainApp.Self.appProcess.getIdGrid(listUser, e, ctMenu);
            DataUserPermission();
            //Lấy dữ liệu từ grid ra text box
            DataGridViewSelectedRowCollection selectRows = listUser.SelectedRows;
            foreach (DataGridViewRow row in selectRows)
            {
                if (row.Cells[0].Value != null)
                {
                    txtUserName.Text = row.Cells[2].Value.ToString();
                    txtFullName.Text = row.Cells[3].Value.ToString();
                    
                    txtAddress.Text = row.Cells[6].Value.ToString();
                    txtPhone.Text = row.Cells[7].Value.ToString();
                    txtEmail.Text = row.Cells[8].Value.ToString();

                    if (row.Cells[4].Value.ToString() == "Đang khóa")
                    {
                        menuLock.Visible = false;
                        menuUnLock.Visible = true;
                        chbActive.Checked = false;
                    }
                    else 
                    {
                        menuLock.Visible = true;
                        menuUnLock.Visible = false;
                        chbActive.Checked = true;
                    }

                    currentRowSelect = listUser.CurrentRow.Index;

                    enableControl(true);

                    if (row.Cells[5].Value.ToString() == "Quản trị hệ thống")
                    {
                        isMasterSelect = true;
                        checkedEnable(false);
                    }
                    else
                    {
                        isMasterSelect = false;
                        checkedEnable(true);
                    }
                }
            }
        }

        private void menuDelete_Click(object sender, EventArgs e)
        {
            doDelete();
        }

        private void btnRenew_Click(object sender, EventArgs e)
        {
            addNewUser();
        }

        private void btnAccept_Click(object sender, EventArgs e)
        {
            if (txtFullName.Text == "" || txtUserName.Text == "" || txtPassWord.Text == "")
            {
                NHTU.MsgBox.Show("Vui lòng nhập đầy đủ các thông tin họ tên, tài khoản , mật khẩu.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                return;
            }

            if (idSelected < 1)
            {
                doSave();
            }
            else
            {
                doUpdate();
            }
        }

        void checkedEnable(bool yes)
        {
            chbActive.Enabled = yes;
            chbTiepNhanHoSo.Enabled = yes;
            chbGiaoHoSo.Enabled = yes;
            chbDuLieuHeThong.Enabled = yes;
            chbNguoiDung.Enabled = yes;
            chbSaoLuu.Enabled = yes;
            chbPhucHoi.Enabled = yes;
            chbGiaoDien.Enabled = yes;
            chbTrinhPheDuyet.Enabled = yes;
            chbPheDuyetQT.Enabled = yes;
            chbBCTongHop.Enabled = yes;
            chbBCHoSoMoi.Enabled = yes;
            chbBCTinhHinhQT.Enabled = yes;
            chbBCTinhHinhHSChuaQT.Enabled = yes;
            chbBCChiTietHSChuaQT.Enabled = yes;
            chbBCChiTietHSDaQT.Enabled = yes;
        }
        void addNewUser() 
        {
            idSelected = -1;
            enableControl(true);
            reloadControl();
            setCheckbox(false, false, false, false, false, false, true, false, false, true, true, true, true, true, true);
        }
        void reloadControl()
        {
            txtFullName.Focus();
            txtFullName.Text = "";
            txtUserName.Text = "";
            txtPassWord.Text = "";
            txtEmail.Text = "";
            txtAddress.Text = "";
            txtPhone.Text = "";
        }
        void enableControl(bool yes)
        {
            txtFullName.Enabled = yes;
            txtUserName.Enabled = yes;
            txtPassWord.Enabled = yes;
            txtEmail.Enabled = yes;
            txtAddress.Enabled = yes;
            txtPhone.Enabled = yes;
            btnAccept.Enabled = yes;
            chbActive.Enabled = yes;
        }
        void setCheckbox(   bool TiepNhanHoSo,
	                        bool GiaoHoSo,
	                        bool DuLieuHeThong,
	                        bool NguoiDung,
	                        bool SaoLuu,
	                        bool PhucHoi,
	                        bool GiaoDien,
	                        bool TrinhPheDuyet,
	                        bool PheDuyetQT,
	                        bool BCTongHop,
	                        bool BCHoSoMoi,
	                        bool BCTinhHinhQT,
	                        bool BCTinhHinhHSChuaQT,
	                        bool BCChiTietHSChuaQT,
	                        bool BCChiTietHSDaQT)
        {
            chbTiepNhanHoSo.Checked=TiepNhanHoSo;
            chbGiaoHoSo.Checked = GiaoHoSo;
            chbDuLieuHeThong.Checked = DuLieuHeThong;
            chbNguoiDung.Checked = NguoiDung;
            chbSaoLuu.Checked = SaoLuu;
            chbPhucHoi.Checked = PhucHoi;
            chbGiaoDien.Checked = GiaoDien;
            chbTrinhPheDuyet.Checked = TrinhPheDuyet;
            chbPheDuyetQT.Checked = PheDuyetQT;
            chbBCTongHop.Checked = BCTongHop;
            chbBCHoSoMoi.Checked = BCHoSoMoi;
            chbBCTinhHinhQT.Checked = BCTinhHinhQT;
            chbBCTinhHinhHSChuaQT.Checked = BCTinhHinhHSChuaQT;
            chbBCChiTietHSChuaQT.Checked = BCChiTietHSChuaQT;
            chbBCChiTietHSDaQT.Checked = BCChiTietHSDaQT;
        }

        private void menuUnLock_Click(object sender, EventArgs e)
        {
            UserDB.lockUser(idSelected,false);
            idSelected = -1;
            enableControl(false);
        }

        private void menuLock_Click(object sender, EventArgs e)
        {
            if (true == isMasterSelect)
            {
                MsgBox.Show("Không thể khóa tài khoản này", "Thông báo", MsgBoxButton.Ok, MsgBoxIcon.Warning);
                return;
            }
            UserDB.lockUser(idSelected, true);
            idSelected = -1;
            enableControl(false);
        }

    }
}
